using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class Lobby : MonoBehaviour
{
    public Text coinsText;
    public Text teslaText;
    public Text levelText;
    public Text countdownText;
    private DateTime endTime;
    private TimeSpan reainingTime;
    private bool isCountingDown = false;
    private string COUNTDOWNKEY = "LobbyCountdownStartTime";
    private int totalHours = 6 * 24;
    public Text day;
    public GameObject redDot;
    public GameObject[] lobbyBtn;
    private int defaultBtnIndex = 1;
    public GameObject[] screens;


    void Awake()
    {
        //监听开始
        GlobalEventManager.OnEvent<float>("UpdateCoins", OnUpdateCoins); //更新金币
        GlobalEventManager.OnEvent<float>("UpdateTesla", OnUpdateTesla); //更新金币
        GlobalEventManager.OnEvent("EliminateRedDots", OnEliminateRedDots); //更新金币
        //监听结束
    }

    void OnDestroy()
    {
        GlobalEventManager.OffEvent<float>("UpdateCoins", OnUpdateCoins); //更新金币
        GlobalEventManager.OffEvent<float>("UpdateTesla", OnUpdateTesla); //更新金币
        GlobalEventManager.OffEvent("EliminateRedDots", OnEliminateRedDots); //更新金币
    }
    void Start()
    {
        float _coins = UserManager.Instance.GetUserInfo()["Coins"].ToObject<float>();
        OnUpdateCoins(_coins);

        float _tesla = UserManager.Instance.GetUserInfo()["Tesla"].ToObject<float>();
        OnUpdateTesla(_tesla);

        // 检查是否已经存储过开始时间
        if (PlayerPrefs.HasKey(COUNTDOWNKEY))
        {
            endTime = DateTime.Parse(PlayerPrefs.GetString(COUNTDOWNKEY));
            isCountingDown = true; // 如果已经存储过开始时间，开始倒计时
        }
        else
        {
            StartCountdown();
        }

        day.text = $"{DateTime.Now.Day}";

        int redDotSt = PlayerPrefs.GetInt("MenuRedDot", 0);
        if (redDotSt == 1)
        {
            redDot.SetActive(false);
        }

        //初始化底部btn
        InitBotBtn();
        ShowScreen();
    }

    private void InitBotBtn()
    {
        for (int i = 0; i < lobbyBtn.Length; i++)
        {
            lobbyBtn[i].transform.Find("Line").gameObject.SetActive(false);
            lobbyBtn[i].transform.Find("Image").DOScale(0.9f, 0.1f);
        }
        lobbyBtn[defaultBtnIndex].transform.Find("Line").gameObject.SetActive(true);
        lobbyBtn[defaultBtnIndex].transform.Find("Image").DOScale(1f, 0.1f);
    }

    public void OnBotBtnClick(int index)
    {
        if (defaultBtnIndex == index) return;
        defaultBtnIndex = index;
        InitBotBtn();

        ShowScreen();
    }

    private async void ShowScreen()
    {
        await FadeManager.Instance.FadeIn();
        for (int i = 0; i < screens.Length; i++)
        {
            screens[i].SetActive(false);
        }
        screens[defaultBtnIndex].SetActive(true);
        switch (defaultBtnIndex)
        {
            case 0:
                Character.Instance.ShowCharacterList();
                break;
        }
        await FadeManager.Instance.FadeOut();
    }

    void Update()
    {
        if (isCountingDown)
        {
            reainingTime = endTime - DateTime.Now;

            if (reainingTime.TotalSeconds <= 0)
            {
                StartCountdown();
            }
            // 更新显示文本
            UpdateCountdownText((float)reainingTime.TotalSeconds);
        }
    }

    void UpdateCountdownText(float remainingTime)
    {
        // 计算剩余的天数、小时数
        int days = Mathf.FloorToInt(remainingTime / (24 * 60 * 60));  // 天数
        int hours = Mathf.FloorToInt((remainingTime % (24 * 60 * 60)) / (60 * 60));  // 小时数
        // int minutes = Mathf.FloorToInt((remainingTime % (60 * 60)) / 60);  // 分钟数
        // int seconds = Mathf.FloorToInt(remainingTime % 60);  // 秒数

        // 更新显示文本
        countdownText.text = $"{days}d {hours}h";
    }

    void StartCountdown()
    {
        endTime = DateTime.Now.AddHours(totalHours);
        PlayerPrefs.SetString(COUNTDOWNKEY, endTime.ToString());
        PlayerPrefs.Save();
        isCountingDown = true;
    }
    void OnEnable()
    {
        if (UserManager.Instance == null) return;
        levelText.text = "Level " + UserManager.Instance.GetUserInfo()["CurrentLv"];
    }

    private void OnUpdateCoins(float coins = 0)
    {
        Debug.Log("更新金币");
        float currtValue = 0;
        DOTween.To(() => currtValue, x => currtValue = x, coins, 1f).OnUpdate(() =>
        {
            coinsText.text = currtValue.ToString("F2");
        });
    }

    private void OnUpdateTesla(float tesla = 0)
    {
        Debug.Log("更新Tesla");
        float currtValue = 0;
        if (float.TryParse(teslaText.text, out float parsedValue))
        {
            currtValue = parsedValue;
        }
        DOTween.To(() => currtValue, x => currtValue = x, tesla, 0.5f).OnUpdate(() =>
        {
            teslaText.text = currtValue.ToString("F2");
        });
    }

    public async void OnLevelClick()
    {
        await FadeManager.Instance.FadeIn();
        Data.mode = 0;
        gameObject.SetActive(false);
        GlobalEventManager.EmitEvent("GameStart");
        await FadeManager.Instance.FadeOut();
    }

    public async void OnDailyClick()
    {
        await FadeManager.Instance.FadeIn();
        Data.mode = 1;
        gameObject.SetActive(false);
        GlobalEventManager.EmitEvent("LimitedTimeMode");
        await FadeManager.Instance.FadeOut();
    }

    public void OnOpenMenuClick()
    {
        // PanelManager.Instance.OpenPanel<FoodMenuPanel>();
    }

    public void OnEliminateRedDots()
    {
        redDot.SetActive(false);
    }
}
